<!--
 * @Description: 
 * @Author: jiaxiuc
 * @Date: 2024-04-25
 * @LastEditors: jiaxiuc
 * @LastEditTime: 2024-04-25
-->
<template>
  <div class="page-wraper">
    <el-button type="primary" icon="el-icon-plus" @click="editBtn()">创建</el-button>
    <!-- <h5 class="page-title">巡检</h5> -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px">
      <el-table-column prop="index" label="序号" width="80"> </el-table-column>
      <el-table-column prop="userName" label="用户名" width="100"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200"> </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="200"> </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editBtn(scope.row)">编辑</el-button>
          <el-button type="text" @click="delBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <el-pagination background @size-change="pageSizeChange" @current-change="currentChange"
    :page-size="pageSize"
    layout="prev, pager, next"
    :total="totalCount">
  </el-pagination> -->
    <!-- 弹窗修改 -->
    <el-dialog :title="form.id ? '编辑管理员' : '创建管理员'" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="form" label-width="80px" :rules="rules" ref="modalForm">
        <el-form-item label="姓名" prop="openId">
          <el-select
            v-model="form.openId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入名称"
            loading-text="加载中...."
            @change="userChange"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option v-for="item in userList" :key="item.openId" :label="item.name" :value="item.openId"
              >{{ item.name || ''
              }}<span v-if="item.departmentName || item.employee_no"
                >（&nbsp;{{ item.departmentName || '' }}&nbsp;&nbsp;{{ item.employee_no || '' }}）</span
              >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button :loading="submiting" type="primary" @click="submitBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CONFIG from '@/config/config'
import storage from '@/utils/storage'
import { adminService, clientService } from '@/api'
export default {
  name: 'Config',
  data() {
    return {
      loading: false,
      submiting: false,
      tableFieIdsObj: {},
      tableData: [],
      //pageSize: 20,
      //totalCount: 100,
      dialogFormVisible: false,
      form: {
        name: '',
      },
      rules: {
        openId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
      },
      userList: [],
    }
  },
  async created() {
    this.token = storage.getItem(CONFIG.TOKEN)
    this.loadData()
  },
  //方法
  methods: {
    async loadData() {
      const res = await adminService.selectHairUser()
      this.tableData = res.result.map((record, index) => {
        return { ...record, index: index + 1 }
      })
      this.$forceUpdate()
    },
    editBtn(data) {
      this.userList = []
      if (data) {
        this.form = JSON.parse(JSON.stringify(data))
        this.remoteMethod(this.form.userName)
      } else {
        this.form = {}
      }
      this.dialogFormVisible = true
      this.$refs.modalForm.resetFields()
    },
    delBtn(data) {
      console.log(data)
      this.$confirm('此操作将删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        adminService.deleteHairUser({ id: data.id }).then((res) => {
          if (res.result) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            this.loadData()
          } else {
            this.$message({
              type: 'error',
              message: res?.error?.msg || '删除失败!',
            })
          }
        })
      })
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    userChange(openId) {
      const user = this.userList.find((record) => record.openId == openId)
      this.form.userName = user?.name || ''
    },
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        let obj = {
          userName: query,
          openId: this.token,
        }
        clientService
          .getUser(obj)
          .then((json) => {
            let res = json.result
            this.loading = false
            if (!json.error) {
              this.userList = res.userList || []
            } else {
              if (json.error.code == 1104 || json.error.code == 99991677) {
                storage.setItem(CONFIG.TOKEN, '')
                this.$router.replace({ name: 'Auth' })
              }
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    async submitBtn() {
      this.$refs.modalForm.validate(async (valid) => {
        if (!valid) {
          return console.log('error submit!!')
        }
        this.submiting = true
        const params = JSON.parse(JSON.stringify(this.form))
        params.level = '1'
        const res = await adminService.addHairUser(params)
        if (res.result) {
          this.$message.success(params.id ? '编辑成功' : '添加成功')
          this.loadData()
          this.dialogFormVisible = false
        } else {
          this.$message.error(res?.error?.msg)
        }
        this.submiting = false
      })
    },
    pageSizeChange() {},
    currentChange() {},
  },
}
</script>
<style lang="less" scoped>
.field-list {
  margin-top: 20px;
  /deep/ .el-row {
    margin-bottom: 16px;
  }
  .field-name {
    font-size: 14px;
  }
}
.desc {
  color: #767676;
  font-size: 12px;
}
</style>
